//
//  AppDelegate.m
//  XiRan-iOS
//
//  Created by Richfit on 2019/10/10.
//  Copyright © 2019 Wood. All rights reserved.
//

#import "AppDelegate.h"
#import "MWNavigationController.h"
#import "MWLaunchController.h"

#import "MWTabBarController.h"
#import "MWXRTabBarController.h"

#import <FBSDKCoreKit/FBSDKCoreKit.h>

@interface AppDelegate ()

@end

@implementation AppDelegate

- (void)configKeyboard {
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    //默认为YES，关闭为NO
    manager.enable = YES;
    //键盘弹出时，点击背景，键盘收回
    manager.shouldResignOnTouchOutside = YES;
    //如果YES，那么使用textField的tintColor属性为IQToolbar，否则颜色为黑色。默认是否定的。
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    //如果YES，则在IQToolbar上添加textField的占位符文本。默认是肯定的。
    manager.shouldShowToolbarPlaceholder = NO;
    //设置IQToolbar按钮的文字
    manager.toolbarDoneBarButtonItemText = @"完成";
    //隐藏键盘上面的toolBar,默认是开启的
    manager.enableAutoToolbar = NO;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self removeLaunchScreenCacheIfNeeded];
    [self loadLocalizableConfig];
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
   
    // 注册微信
    [WXApi registerApp:@"wx1a2a08ed9edba292" universalLink:@"https://d-chengshilieren.bigchun.com/woodhunter/"];
    // Facebook
    [[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    [FBSDKSettings setAppID:@"1091407657896199"];
    
    [self configKeyboard];
    [[MWUserManager manager] loadUser];
    [[MWConfigManager manager] loadConfig];
    
    [self cheackNetWoking];
    MWLaunchController *launchController = [[MWLaunchController alloc] init];
    self.window.rootViewController = launchController;
    [self.window makeKeyAndVisible];
    
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application
                                                                  openURL:url
                                                        sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]
                                                               annotation:options[UIApplicationOpenURLOptionsAnnotationKey]
                    ];
    [WXApi handleOpenURL:url delegate:[MWWXApiManager sharedManager]];
    
    return YES;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return  [WXApi handleOpenURL:url delegate:[MWWXApiManager sharedManager]];
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {
    return [WXApi handleOpenUniversalLink:userActivity delegate:[MWWXApiManager sharedManager]];
}

#pragma mark - 国际化配置常量
- (void)loadLocalizableConfig {
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    if ([[MWConfigManager manager].language isEqualToString:@"0"]) {
        [paraDic setObject:@"zh" forKey:@"lang"];
    } else if ([[MWConfigManager manager].language isEqualToString:@"2"]) {
        [paraDic setObject:@"ja" forKey:@"lang"];
    } else {
        [paraDic setObject:@"en" forKey:@"lang"];
    }
    
    [[MWNetworkManager manager] POST:kLocalizableConfigUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
        if (code == 1) {
            [MWConfigManager manager].localizableDic = [dic objectForKey:@"data"];
            [[MWConfigManager manager] saveConfig];
            [MWLocalizableManager configCopywriter];
        }
        
    } failure:^(NSError *error) {
        
    }];
}

- (void)cheackNetWoking {
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        self.isNeedRequest = (self.reachabilityStatus<1);
        self.reachabilityStatus = status;
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWiFi: { // @"WiFi网络"
            }
                break;
            case AFNetworkReachabilityStatusNotReachable: {
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
                hud.label.text = [[MWConfigManager manager] objectForKey:@"network_error" defaultValue:@"未连接任何网络，检查网络后重试"];
                hud.mode = MBProgressHUDModeText;
                [hud hideAnimated:YES afterDelay:2];
                
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN: { // @"移动网络"
            }
                break;
                
            default: {
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
                hud.label.text = [[MWConfigManager manager] objectForKey:@"network_error" defaultValue:@"未知网络"];
                hud.mode = MBProgressHUDModeText;
                [hud hideAnimated:YES afterDelay:2];
                
            }
                break;
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:kNetWorkStatusNotification object:nil];
    }];
}

// 为了每次都读取最新的启动图，所以要在有缓存的时候清除缓，
- (void)removeLaunchScreenCacheIfNeeded {
   NSString *filePath = [NSString stringWithFormat:@"%@/Library/SplashBoard", NSHomeDirectory()];
   
   if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
    NSError *error = nil;
    [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];

    if (error) {
         NSLog(@"清除LaunchScreen缓存失败");
       } else {
         NSLog(@"清除LaunchScreen缓存成功");
       }
    }
}


@end
